package com.sec.typhoondatapush.util;

import com.sec.typhoondatapush.config.SpringUtils;
import com.sec.typhoondatapush.entity.JobConfig;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;

/**
 * @Description: : 通过job配置的DB获取要执行的job的class和方法名，通过动态加载的方式执行定时任务要执行的方法
 * @date :Create in  2018/7/30- 16:12
 * @Version: V1.0
 * @Modified By: zhuwq
 **/
@Slf4j
public class TaskUtils {

    public static void invokMethod(JobConfig jobConfig) {
        Object obj = null;
        Class clazz = null;
        //通过Spring上下文去找 也有可能找不到
        try {
            obj = SpringUtils.getBean(jobConfig.getClassPath().split("\\.")[jobConfig.getClassPath().split("\\.").length - 1]);
            if (obj == null) {
                clazz = Class.forName(jobConfig.getClassPath());
                obj = clazz.newInstance();
            } else {
                clazz = obj.getClass();
            }
        } catch (Exception e) {
            throw new RuntimeException("ERROR:TaskUtils is Bean Create please check the classpath is`t right or not");
        }
        Method method = null;
        //获得方法名
        try {
            method = clazz.getDeclaredMethod(jobConfig.getMethodName());
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("ERROR:TaskUtils is Bean the method Create please check the methodName is`t right or not");
        }
        //方法执行
        try {
            method.invoke(obj);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException("ERROR:TaskUtils is Bean the method execute please check the methodName is`t right or not");
        }

    }
}
